EzyHTTP Download File
Updated at 1685686563000Same as every HTTP server framewords, EzyHttp allows you download file, too. And we recommend you use asynchronous API, to know why, please take a look the explanation here.
1. ResourceRequestHandler
EzyHTTP provides to you an convenient FileUploader
class. It uses ResourceDownloadManager
, an event loop like below:
And the event loop will do like this:
loop: take a outputstream/file inputstream pair from the queue: take 1024 bytes from the file inputstream of the requested file and push to client's outputstream if there is no remain data in the file inputstream then response to the client: call to the callback and done else push the the inputstream/outputstream pair back to the queue
2. Enable file download configuration
To enable file download, you can add the configuration to your application.properties file like this:
resources.enable=true
If you want to set queue capacity and thread pool size, buffer size, you can setup:
resources.download.capacity=[an integer value] resources.download.thread_pool_size=[an integer value] resources.download.buffer_size=[an integer value]
3. Download file asynchronously
To download a file asynchronously with ResourceRequestHandler, you can do like this:
@Controller("/api/v1") @AllArgsConstructor public class FileController { private final FileDownloadService fileDownloadService; @Async @DoGet("/files/{file}") public void downloadGet( RequestArguments requestArguments, @PathVariable("file") String file, @RequestHeader("token") String token ) throws Exception { if (EzyStrings.isBlank(token)) { throw new HttpBadRequestException("token can not be null"); } fileDownloadService.download(requestArguments, file); } } @EzySingleton @AllArgsConstructor public class FileDownloadService { private final ResourceDownloadManager resourceDownloadManager; public void download( RequestArguments requestArguments, String file ) throws Exception { ResourceRequestHandler handler = new ResourceRequestHandler( "files/" + file, "files/" + file, EzyFileUtil.getFileExtension(file), resourceDownloadManager ); handler.handle(requestArguments); } }
4. Download file Synchronously
To download a file synchronously, you can do like this:
@Controller("/api/v1") @AllArgsConstructor public class FileController { @DoGet("/files/{file}") public ResponseEntity downloadGet( HttpServletResponse response, @PathVariable("file") String file ) throws Exception { try (InputStream inputStream = new FileInputStream(file)) { OutputStream outputStream = response.getOutputStream(); byte[] buffer = new byte[1024]; while (true) { int read = inputStream.read(buffer); if (read > 0) { outputStream.write(buffer, 0, read); } else { break; } } } return ResponseEntity.noContent(); } }
Next step
You can see how to create a website.